package com.ht.WeNas;

import cn.hutool.socket.SocketRuntimeException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.cache.annotation.EnableCaching;

import java.io.IOException;
import java.net.ServerSocket;

@Slf4j
@SpringBootApplication
@EnableCaching
public class NasApplication {
    private static final int[] defaultPorts = {
            80, 8080, 10000, 10010
    };

    private static int getPort() {
        for (int port : defaultPorts) {
            if (checkSocketUsable(port)) {
                return port;
            }
        }
        int port = defaultPorts[defaultPorts.length - 1];
        while (!checkSocketUsable(++port) || port > 49151) {}
        if (port == 49151) {
            throw new SocketRuntimeException("没有可用端口");
        } else {
            return port;
        }
    }
    
    private static boolean checkSocketUsable(int port) {
        try (ServerSocket socket = new ServerSocket(port)) {
            return true;
        } catch (IOException e) {
            return false;
        }
    }
    
    public static void main(String[] args) {
        SpringApplicationBuilder applicationBuilder = new SpringApplicationBuilder(NasApplication.class);
        boolean isDev = false;
        for (String arg : args) {
            if ("dev".equals(arg)) {
                isDev = true;
                break;
            }
        }
        int port = isDev ? 8080 : getPort();
        applicationBuilder.properties("server.port=" + port);
        applicationBuilder.run(args);
        System.out.println("请访问:http://127.0.0.1:" + port);
    }
}
